/* Copyright 2011 Thomas R. Mackel (tmackel@gmail.com) */

package com.civtechtracker;

import java.util.List;
import java.util.Random;

import com.google.ads.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class CivTechTracker extends Activity implements AdListener {
	private TechListManager techManager = new TechListManager(this);
	private ScrollView parentView;
	private AdView av;
	private SharedPreferences preferences;
	private AdClickManager adManager = new AdClickManager();
	private Random randInt = new Random();
	private AdRequest request = new AdRequest();
	private TextView adRemoveInfoView;
	private LinearLayout pageView;
	private LinearLayout cartView;
	private TextView cartInfo;
	private Boolean cartMode = false;

	private Integer darkenColor(Integer inColor) {
		int alpha = Color.alpha(inColor);
		int red = Color.red(inColor);
		int green = Color.green(inColor);
		int blue = Color.blue(inColor);

		return Color.argb(alpha / 8, red, green, blue);
	}

	private Integer mean(Integer a, Integer b) {
		return (a + b) / 2;
	}

	private Integer mergeColors(Integer c1, Integer c2) {
		int a1 = Color.alpha(c1);
		int r1 = Color.red(c1);
		int g1 = Color.green(c1);
		int b1 = Color.blue(c1);

		int a2 = Color.alpha(c2);
		int r2 = Color.red(c2);
		int g2 = Color.green(c2);
		int b2 = Color.blue(c2);

		return Color.argb(mean(a1, a2), mean(r1, r2), mean(g1, g2),
				mean(b1, b2));
	}

	private void showDescription(Integer tId) {
		Tech t = techManager.getTechById(tId);
		String message = t.name + ": " + t.desc + "\n\n" + getString(R.string.credit_to_text) + ":";
		if (t.credits.size() > 0) {
			for (Credit c : t.credits) {
				message = message + "\n" + c.amount.toString() + " "
						+ c.creditTowards;
			}
		} else {
			message = message + "\n" + getString(R.string.not_applicable_text);
		}
		message = message + "\n\n" +  getString(R.string.credit_from_text) + ":";
		List<Credit> creditProviders = techManager.getCreditProviders(t.name);
		if (creditProviders.size() > 0) {
			for (Credit c : creditProviders) {
				message = message + "\n" + c.amount.toString() + " "
						+ c.creditTowards;
			}
		} else {
			message = message + "\n" + getString(R.string.not_applicable_text);
		}

		AlertDialog ad = new AlertDialog.Builder(this).create();
		ad.setMessage(message);
		ad.setButton(getString(R.string.ok_text), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		ad.show();
	}

	private void updateDisplay() {
		// LinearLayout pageView = new LinearLayout(this);
		pageView = new LinearLayout(this);
		pageView.setOrientation(LinearLayout.VERTICAL);
		List<Tech> techList = techManager.getAllTechs();
		Integer prevRowColor = techList.get(0).primaryColor;
		Integer nextRowColor;
		for (int i = 0; i < techList.size(); i++) {
			Tech t = techList.get(i);
			LinearLayout rowView = (LinearLayout) LayoutInflater.from(this)
					.inflate(R.layout.rowtemplate, null);
			TextView costView = (TextView) rowView.getChildAt(0);
			TextView techView = (TextView) rowView.getChildAt(1);
			GradientDrawable gd = new GradientDrawable(
					GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
							t.primaryColor, t.primaryColor, t.primaryColor,
							t.secondaryColor, t.secondaryColor,
							t.secondaryColor });

			if (i + 1 < techList.size()) {
				nextRowColor = techList.get(i + 1).primaryColor;
			} else {
				nextRowColor = techList.get(i).secondaryColor;
			}
			GradientDrawable dimGd = new GradientDrawable(
					GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
							darkenColor(mergeColors(prevRowColor,
									t.primaryColor)),
							darkenColor(mergeColors(nextRowColor,
									t.secondaryColor)) });
			costView.setBackgroundDrawable(gd);
			rowView.setBackgroundDrawable(dimGd);
			prevRowColor = t.secondaryColor;

			if (t.owned) {
				costView.setText("\u2714");
				costView.setTextColor(Color.DKGRAY);
				costView.setTextSize((int) (costView.getTextSize() + 1));
			} else if (cartMode && t.inCart) {
				costView.setText("\u2714");
				costView.setTextColor(Color.WHITE);
				costView.setTextSize((int) (costView.getTextSize() + 1));
			} else {
				costView.setText(t.displaycost.toString());
			}

			final Tech techClicked = t;
			costView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					addOrRemoveTech(techClicked);
					updateDisplay();
				}
			});
			techView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					addOrRemoveTech(techClicked);
					updateDisplay();
				}
			});

			techView.setText(t.name);
			techView.setLongClickable(true);
			final Integer techId = t.id;
			costView.setOnLongClickListener(new OnLongClickListener() {
				public boolean onLongClick(View v) {
					showDescription(techId);
					return true;
				}
			});
			techView.setOnLongClickListener(new OnLongClickListener() {
				public boolean onLongClick(View v) {
					showDescription(techId);
					return true;
				}
			});

			if (null != t.prereq) {
				Tech pre = techManager.getTechByName(t.prereq);
				if (!pre.owned) {
					costView.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
						}
					});
					techView.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
						}
					});
					techView.setText(t.name + " (" +  getString(R.string.requires_text) + " " + t.prereq + ")");
					techView.setTextColor(Color.GRAY);
				}
			}

			pageView.addView(rowView);
		}
		
		updateCart();
		
		parentView.removeAllViews();
		parentView.addView(pageView);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(getString(R.string.reset_text));
		menu.add(getString(R.string.score_text));
		menu.add(getString(R.string.mode_text));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals(getString(R.string.reset_text))) {
			techManager.init(); // action = reset
		} else if (item.getTitle().equals(getString(R.string.score_text))) {
			Toast.makeText(
					this,
					getString(R.string.you_own_text) + " " + String.valueOf(techManager.getPoints())
							+ " " + getString(R.string.points_text), Toast.LENGTH_LONG).show();
		} else if (item.getTitle().equals(getString(R.string.mode_text))) {
			cartMode = !cartMode;
			if (cartMode) {
				AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
				alertbox.setMessage(getString(R.string.cart_mode_desc));
				alertbox.setNeutralButton(getString(R.string.ok_text), null);
				alertbox.show();
				cartView.setVisibility(View.VISIBLE);
			} else {
				AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
				alertbox.setMessage(getString(R.string.default_mode_desc));
				alertbox.setNeutralButton(getString(R.string.ok_text), null);
				alertbox.show();
				cartView.setVisibility(View.GONE);
			}
		}
		updateDisplay();
		return true;
	}

	private void addOrRemoveTech(Tech clickedTech){
		if (cartMode){
			if (clickedTech.inCart){
				techManager.removeFromCart(clickedTech.id);
			}
			else{
				techManager.addToCart(clickedTech.id);
			}
		}
		else{
			if (clickedTech.owned){
				techManager.unbuyTech(clickedTech.id);
			}
			else{
				techManager.buyTech(clickedTech.id);
			}
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		preferences = getPreferences(MODE_PRIVATE);
		techManager.loadStateInfo(preferences);
		parentView = new ScrollView(this); // Root view of application
		
		updateDisplay();
		this.setContentView(R.layout.main);
		av = (AdView) findViewById(R.id.ads);
		av.setAdListener(this);

		adRemoveInfoView = (TextView) findViewById(R.id.ad_remove_info);
		cartView = (LinearLayout) findViewById(R.id.cart_info_layout);
		cartInfo = (TextView) findViewById(R.id.cart_info);
		
		LinearLayout homeView = (LinearLayout) findViewById(R.id.home_layout);
		homeView.addView(parentView);
		
		updateCart();
	}
	
	private void updateCart(){
		if (cartMode) {
			cartView.setVisibility(View.VISIBLE);
			cartInfo.setText(getString(R.string.items_text) + ": \t"
					+ techManager.getCartQty().toString() + "\n"
					+ getString(R.string.total_text) + ": \t" + techManager.getCartTotal().toString());
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onPause() {
		super.onPause();
		SharedPreferences.Editor editor = preferences.edit();
		editor.putBoolean("cartMode", cartMode);
		editor.commit();
		techManager.saveStateInfo(preferences);
	}

	@Override
	public void onResume() {
		super.onResume();
		preferences = getPreferences(MODE_PRIVATE);
		cartMode = preferences.getBoolean("cartMode", false);
		techManager.loadStateInfo(preferences);
		if (adManager.showAd(preferences)) {
			// request.addTestDevice(AdRequest.TEST_EMULATOR);
			// request.addTestDevice("B67C2CB88D0606891DE3235BA02DE637");
			if (randInt.nextInt(4) > 0) {
				adRemoveInfoView.setVisibility(View.GONE);
				av.setVisibility(View.VISIBLE);
				av.loadAd(request);
			} else {
				adRemoveInfoView.setVisibility(View.VISIBLE);
				av.setVisibility(View.GONE);
			}
		} else {
			av.setVisibility(View.GONE);
			adRemoveInfoView.setVisibility(View.GONE);
		}
		/*
		 * String lastClick = "Last Ad Clicked on " +
		 * String.valueOf(preferences.getInt("lastClickMonth", -1) + 1) + "/" +
		 * String.valueOf(preferences.getInt("lastClickDay", -1)) + "/" +
		 * String.valueOf(preferences.getInt("lastClickYear", -1)); Toast
		 * adDebug = Toast.makeText(this, lastClick, Toast.LENGTH_SHORT);
		 * adDebug.show();
		 */
		updateCart();
		updateDisplay();
	}

	@Override
	public void onSaveInstanceState(Bundle b) {
		super.onSaveInstanceState(b);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putBoolean("cartMode", cartMode);
		editor.commit();
		techManager.saveStateInfo(preferences);
		b.putInt("scrollX", parentView.getScrollX());
		b.putInt("scrollY", parentView.getScrollY());
		//b.putBoolean("cartMode", cartMode);
	}

	@Override
	public void onRestoreInstanceState(Bundle b) {
		super.onRestoreInstanceState(b);
		preferences = getPreferences(MODE_PRIVATE);
		techManager.loadStateInfo(preferences);
		//cartMode = b.getBoolean("cartMode");
		cartMode = preferences.getBoolean("cartMode", false);
		try {
			final int currentX = b.getInt("scrollX");
			final int currentY = b.getInt("scrollY");
			parentView.post(new Runnable() {
				public void run() {
					parentView.scrollTo(currentX, currentY);
				}
			});
		} catch (Exception e) {
		}
		updateCart();
	}

	public TechListManager getTechListManagerHandle() {
		return techManager;
	}

	public SharedPreferences getPreferencesHandle() {
		return preferences;
	}

	public void buyTechsInCart(View view) {
		techManager.buyTechsInCart();
		updateDisplay();
	}

	// AdListener Interface
	public void onPresentScreen(Ad ad) {
		adManager.setLastClick(preferences);
	}

	public void onReceiveAd(Ad ad) {
	}

	public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
	}

	public void onDismissScreen(Ad ad) {
	}

	public void onLeaveApplication(Ad ad) {
		adManager.setLastClick(preferences);
	}
}